package com.example.illuminator.interceptor;

import Tools.Encryption.JWTEncryption;
import Tools.Exception.illuminatorStatus;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.example.illuminator.config.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        Result result = null;
        if(token == null){
            result = Result.error(illuminatorStatus.TokenError);
        }else{
            try {
                JWTEncryption.verify(token);
                return true;
            }catch (SignatureVerificationException e){
                e.printStackTrace();
                result = Result.error(illuminatorStatus.TokenInvalidSignature);
            }catch (TokenExpiredException e){
                e.printStackTrace();
                result = Result.error(illuminatorStatus.TokenTimeOut);
            }catch (AlgorithmMismatchException e){
                e.printStackTrace();
                result = Result.error(illuminatorStatus.TokenErrorAlg);
            }catch (Exception e){
                e.printStackTrace();
                result = Result.error(illuminatorStatus.TokenError);
            }
        }
        String json = new ObjectMapper().writeValueAsString(result);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().print(json);
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
